package com.sl.carcode.utils;

import android.util.ArrayMap;

import com.google.gson.Gson;
import com.sl.carcode.bean.CarInfo;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * Created by admin on 2017/9/1.
 */

public class GsonUtils {
    public static Object json2Object(String str, Class<?> cls) {
        Gson gson = new Gson();
        return gson.fromJson(str, cls);
    }

    public static ArrayList jsonArray2List(String str, Class<?> cls) {
        ArrayList list = new ArrayList();
        try {
            JSONArray jsonArray = new JSONArray(str);
            for (int i = 0; i < jsonArray.length(); i++) {
                Gson gson = new Gson();
                list.add(gson.fromJson(jsonArray.getString(i).toString(), cls));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return list;
    }

    public static ArrayMap<String, CarInfo> getCarCodeList(String json) {
        ArrayMap map = new ArrayMap();
        Gson gson = new Gson();
        try {
            JSONArray jsonArray = new JSONArray(json);
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = (JSONObject) jsonArray.get(i);
                CarInfo carInfo = gson.fromJson(jsonObject.toString(), CarInfo.class);
                map.put(carInfo.getCode(), carInfo);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return map;
    }
}
